package 俄罗斯方块接口.frame;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


/**
 * 带双缓冲功能的窗体
 */
@SuppressWarnings("serial")
public class BufferFrame extends NormalFrame implements Runnable {

	/**
	 * 离屏图片
	 */
	private Image offScreenImage;
	

	/**
	 * 标记窗体是否正在自动刷新
	 */
	private boolean running = true;

	/**
	 * 获得一个大小为width x height大小的双缓冲窗体
	 */
	public static BufferFrame getBufferFrame(int width, int height) {
		BufferFrame bf = new BufferFrame(width, height);
		return bf;
	}
	
	/**
	 * 新建一个大小为width x height大小的双缓冲窗体
	 * @param width 	宽度
	 * @param height 	高度
	 */
	public BufferFrame(int width, int height) {
		super(width, height);
		new Thread(this).start();
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				running = false;
			}
		});
	}
	
	public void update(Graphics g) {
		if(offScreenImage == null) {
			offScreenImage = this.createImage(this.getWidth(), this.getHeight());
		}
		Graphics gOff = offScreenImage.getGraphics();
		Color c = gOff.getColor();
		gOff.setColor(this.getBackground());
		gOff.fillRect(0, 0, this.getWidth(), this.getHeight());
		gOff.setColor(c);
		paint(gOff);
		g.drawImage(offScreenImage, 0, 0, null);
	}

	public void run() {
//		long T1 = System.currentTimeMillis();
//		long T2 = System.currentTimeMillis();
//		while(running) {
//			if(T2 - T1 > 10) {
//				repaint();
//				T1 = System.currentTimeMillis();
//			}
//			T2 = System.currentTimeMillis();
//		}
		while(running) {
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
			repaint();
	}
	}
}
